package com.coollang.smartbra.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.coollang.smartbra.R;

import java.util.ArrayList;
import java.util.List;



public class MapUtil {
    public static final String GPS = "gps";
    static Bitmap result = null;
    private static PolylineOptions mPolyoptions;
    private static AMap mMap;
    private static List<Long> timePointList;

    /**
     * 对地图进行截屏
     */
    public static Bitmap getMapScreenshot(final Activity activity, AMap aMap, final Bitmap viewBitmap, final int w, final int h, final Bitmap gpsBitmap) {
        aMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
            @Override
            public void onMapScreenShot(Bitmap bitmap) {
            }

            @Override
            public void onMapScreenShot(Bitmap bitmap, int status) {
                if (null == bitmap) {
                    return;
                }
                if (status != 0) {
                    //                    "地图渲染完成，截屏无网格"
                    result = BitmapUtils.addBitmap(bitmap, viewBitmap, w, h, gpsBitmap);
                    // new ShareBitmapDialog(activity, result).show();
                } else {
//                    "地图未渲染完成，截屏有网格"
                }

            }
        });
        return result;
    }


    /**
     * 将AMapLocation List 转为TraceLocation list
     *
     * @param list
     * @return
     */
    public static List<TraceLocation> parseTraceLocationList(
            List<AMapLocation> list) {
        List<TraceLocation> traceList = new ArrayList<TraceLocation>();
        if (list == null) {
            return traceList;
        }
        for (int i = 0; i < list.size(); i++) {
            TraceLocation location = new TraceLocation();
            AMapLocation amapLocation = list.get(i);
            location.setBearing(amapLocation.getBearing());
            location.setLatitude(amapLocation.getLatitude());
            location.setLongitude(amapLocation.getLongitude());
            location.setSpeed(amapLocation.getSpeed());
            location.setTime(amapLocation.getTime());
            traceList.add(location);
        }
        return traceList;
    }

    /**
     * 将AMapLocation List 转为LatLng list
     *
     * @param list
     * @return
     */
    public static List<LatLng> parseLatLngList(List<AMapLocation> list) {
        List<LatLng> traceList = new ArrayList<LatLng>();
        if (list == null) {
            return traceList;
        }
        for (int i = 0; i < list.size(); i++) {
            AMapLocation loc = list.get(i);
            double lat = loc.getLatitude();
            double lng = loc.getLongitude();
            LatLng latlng = new LatLng(lat, lng);
            traceList.add(latlng);
        }
        return traceList;
    }

    public static AMapLocation parseLocation(String latLonStr) {
        if (latLonStr == null || latLonStr.equals("") || latLonStr.equals("[]")) {
            return null;
        }
        String[] loc = latLonStr.split(",");
        AMapLocation location = null;
        if (loc.length == 6) {
            location = new AMapLocation(loc[2]);
            location.setProvider(loc[2]);
            location.setLatitude(Double.parseDouble(loc[0]));
            location.setLongitude(Double.parseDouble(loc[1]));
            location.setTime(Long.parseLong(loc[3]));
            location.setSpeed(Float.parseFloat(loc[4]));
            location.setBearing(Float.parseFloat(loc[5]));
        } else if (loc.length == 2) {
            location = new AMapLocation(GPS);
            location.setLatitude(Double.parseDouble(loc[0]));
            location.setLongitude(Double.parseDouble(loc[1]));
        }
        return location;
    }

    public static ArrayList<AMapLocation> parseLocations(String latLonStr) {
        ArrayList<AMapLocation> locations = new ArrayList<AMapLocation>();
        String[] latLonStrs = latLonStr.split(";");
        for (int i = 0; i < latLonStrs.length; i++) {
            AMapLocation location = parseLocation(latLonStrs[i]);
            if (location != null) {
                locations.add(location);
            }
        }
        return locations;
    }

    public static LatLng getLocationLatLng(AMapLocation aMapLocation) {
        return new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
    }

    //*************************************绘制轨迹******************************************//
    public static LatLngBounds getBounds(List<LatLng> mOriginLatLngList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (mOriginLatLngList == null) {
            return b.build();
        }
        for (int i = 0; i < mOriginLatLngList.size(); i++) {
            b.include(mOriginLatLngList.get(i));
        }
        return b.build();
    }

    public static void redrawlineLive(PolylineOptions mPolyoptions, final AMap mMap, List<Long> timePointList, ArrayList<String> pauseList) {
        if (mPolyoptions.getPoints().size() >= 2) {
            addOriginTrace(mPolyoptions.getPoints().get(0), mPolyoptions.getPoints().get(mPolyoptions.getPoints().size() - 1), mPolyoptions.getPoints(), mMap, timePointList, pauseList);
        }
    }

    public static void redrawlineLiveL(PolylineOptions mPolyoptions, final AMap mMap, List<Long> timePointList, boolean pause) {
        if (mPolyoptions.getPoints().size() >= 2) {
            addGraspTrace(mPolyoptions.getPoints(), mMap, timePointList, pause);
        }
    }

    /**
     * 轨迹纠偏
     *
     * @param mPolyoptions
     * @param mMap
     * @param aMapLocationList
     * @param timePointList
     * @param isPause
     */
    public static void redrawline(PolylineOptions mPolyoptions, final AMap mMap, List<AMapLocation> aMapLocationList, final List<Long> timePointList, final boolean isPause) {
        if (mPolyoptions.getPoints().size() > 2) {
            // 轨迹纠偏初始化
            LBSTraceClient mTraceClient = new LBSTraceClient(UIUtils.getContext());
            List<TraceLocation> mGraspTraceLocationList = MapUtil.parseTraceLocationList(aMapLocationList);
            // 调用轨迹纠偏，将mGraspTraceLocationList进行轨迹纠偏处理
            mTraceClient.queryProcessedTrace(1, mGraspTraceLocationList, LBSTraceClient.TYPE_AMAP, new TraceListener() {
                @Override
                public void onRequestFailed(int i, String s) {
//                    Toast.makeText(UIUtils.getContext(), "轨迹纠偏失败:" + s, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onTraceProcessing(int i, int i1, List<LatLng> list) {

                }

                @Override
                public void onFinished(int i, List<LatLng> list, int i1, int i2) {
                    addGraspTrace(list, mMap, timePointList, isPause);
                }
            });
//			addOriginTrace(mPolyoptions.getPoints().get(0), mPolyoptions.getPoints().get(mPolyoptions.getPoints().size() - 1), mPolyoptions.getPoints(),mMap);
        }
    }

    /**
     * 地图上添加纠偏后轨迹线路及起终点、轨迹动画小人
     */
    private static void addGraspTrace(List<LatLng> graspList, AMap mMap, List<Long> timePointList, boolean isPause) {
        if (originListChange != null && originListChange.size() > 0) {
            originListChange.clear();
        }
        if (graspList == null || graspList.size() < 2) {
            return;
        }
        List<Integer> colorList = getColorList(graspList, timePointList);
        LatLng startPoint = originListChange.get(0);
        LatLng endPoint = originListChange.get(originListChange.size() - 1);
        if (isPause) {
            //暂停绘制虚线
            mOriginPolyline = mMap.addPolyline(new PolylineOptions().zIndex(1).width(15).setDottedLine(true).color(UIUtils.getColor(R.color.dott)).useGradient(true).addAll(originListChange));
        } else {
            mOriginPolyline = mMap.addPolyline(new PolylineOptions().zIndex(1).width(15).setDottedLine(false).colorValues(colorList).useGradient(true).addAll(originListChange));
        }
        if (mOriginEndMarker != null) {
            mOriginEndMarker.destroy();
        }
        if (mOriginStartMarker != null) {
            mOriginStartMarker.destroy();
        }
        //添加图钉
        mOriginStartMarker = mMap.addMarker(new MarkerOptions().zIndex(1).position(startPoint).icon(BitmapDescriptorFactory.fromResource(R.drawable.start)).setFlat(true));
        mOriginEndMarker = mMap.addMarker(new MarkerOptions().zIndex(1).position(endPoint).icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }

    private static Marker mGraspStartMarker, mGraspEndMarker;
    private static Polyline mGraspPolyline;
    private static List<LatLng> mGraspLatLngList;
    private static Polyline mOriginPolyline;
    private static Marker mOriginEndMarker, mOriginStartMarker;

    /**
     * 地图上添加原始轨迹线路及起终点、轨迹动画小人
     *
     * @param startPoint
     * @param endPoint
     * @param originList
     * @param timePointList
     * @param pauseList
     */
    public static void addOriginTrace(LatLng startPoint, LatLng endPoint, List<LatLng> originList, AMap mMap, List<Long> timePointList, ArrayList<String> pauseList) {
        if (originListChange != null && originListChange.size() > 0) {
            originListChange.clear();
        }
        if (originList == null || originList.size() < 2) {
            return;
        }
        List<Integer> colorList = getColorList(originList, timePointList);
        startPoint = originListChange.get(0);
        endPoint = originListChange.get(originListChange.size() - 1);
        for (int i = 0; i < pauseList.size(); i++) {
            if ("0".equals(pauseList.get(i))) {
                //暂停
                mOriginPolyline = mMap.addPolyline(new PolylineOptions().zIndex(1).width(15).setDottedLine(true).color(UIUtils.getColor(R.color.dott)).useGradient(true).addAll(originListChange));
            } else {
                mOriginPolyline = mMap.addPolyline(new PolylineOptions().zIndex(1).width(15).colorValues(colorList).useGradient(true).addAll(originListChange));
            }
        }
        if (mOriginEndMarker != null) {
            mOriginEndMarker.destroy();
        }
        if (mOriginStartMarker != null) {
            mOriginStartMarker.destroy();
        }
        //添加图钉
        mOriginStartMarker = mMap.addMarker(new MarkerOptions().zIndex(1).position(startPoint).icon(BitmapDescriptorFactory.fromResource(R.drawable.start)).setFlat(true));
        mOriginEndMarker = mMap.addMarker(new MarkerOptions().zIndex(1).position(endPoint).icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }

    /**
     * 移到当前定位的位置
     *
     * @param aMapLocation
     */
    public static void moveCurrentPostion(AMapLocation aMapLocation, AMap mMap) {
        mMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
    }

    static List<LatLng> originListChange = new ArrayList<LatLng>();

    //计算两点之间距离计算速度来设置绘制的颜色   originList.size必须大于2才能成线段
    public static List<Integer> getColorList(List<LatLng> originList, List<Long> timePointList) {
        List<Integer> colorList = new ArrayList<Integer>();
        List<LatLng> originListTwo = originList;
        for (int i = 0; i < originListTwo.size(); i++) {
            if (i + 1 > originListTwo.size() - 1) {
                originListChange.add(originListTwo.get(originListTwo.size() - 1));
                break;
            } else {
                double d = AMapUtils.calculateLineDistance(originListTwo.get(0 + i), originListTwo.get(1 + i));
                Long time = timePointList.get(i + 1) - timePointList.get(i);
                float s = (float) (d / (float) time);
                if (s >= 12) {
                    originListTwo.remove(i + 1);
                    continue;
                } else {
                    // MapActivity.saveRunDetailPointDataToDB(originList.get(i).latitude, originList.get(i).longitude, timePointList.get(i), isPause);
                    colorList.add(Color.rgb((int) Math.min(101 + s * 10, 238), (int) Math.max(233 - s * 15, 69), (int) Math.max(129 - s * 5, 69)));
                    originListChange.add(originListTwo.get(i));
                }
            }
        }
        return colorList;
    }
}
